/*
 * @描述: 数据权限页面逻辑
 * @版权所有: 广东国星科技有限公司
 * @商业授权: www.mscodecloud.com
 */
import React, { PureComponent, Fragment } from 'react';
import { formatMessage } from 'umi-plugin-react/locale';
import { connect } from 'dva';
import moment from 'moment';
import { Row, Col, Card, Form, Input, Select, Icon, Button, message, Radio, Popconfirm, Drawer, Table } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import ProTable from '@ant-design/pro-table';

import styles from './Admin.less';

const FormItem = Form.Item;
const { Option } = Select;
const RadioGroup = Radio.Group;
const InputGroup = Input.Group;
const InputPassword = Input.Password;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');

// 带单元格编辑功能的表格
const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  state = {
    editing: false,
  };

  toggleEdit = () => {
    const editing = !this.state.editing;
    this.setState({ editing }, () => {
      if (editing) {
        this.input.focus();
      }
    });
  };

  save = e => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }
      this.toggleEdit();
      handleSave({ ...record, ...values });
    });
  };

  renderCell = form => {
    this.form = form;
    const { children, dataIndex, record /** , title **/ } = this.props;
    const { editing } = this.state;
    return editing ? (
      <Form.Item style={{ margin: 0 }}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            {
              required: true,
              message: formatMessage({ id: 'app.common.required' })
            },
          ],
          initialValue: record[dataIndex],
        })(
          dataIndex === 'roleCode' ?
            <Select ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save} placeholder={formatMessage({ id: 'app.common.choose' })} style={{ width: '100%' }}>
              {window.roleData && window.roleData.map(d => (
                <Option key={d.value}>{d.name}</Option>
              ))}
            </Select>
            :
            <Input ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save} />
        )}
      </Form.Item>
    ) : (
        <div
          className="editable-cell-value-wrap"
          style={{ paddingRight: 24 }}
          onClick={this.toggleEdit}
        >
          {children}
        </div>
      );
  };

  render() {
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editable ? (
          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
        ) : (
            children
          )}
      </td>
    );
  }
}

// 包含带单元格编辑功能的表格的抽屉
@Form.create()
class UpdateForm extends PureComponent {
  static defaultProps = {
    handleUpdateModalVisible: () => { },
    values: {}
  };

  constructor(props) {
    super(props);
    this.columns = [
      {
        title: formatMessage({ id: 'app.sysrole.role-code' }),
        dataIndex: 'roleCode',
        width: '30%',
        editable: true,
      },
      {
        title: formatMessage({ id: 'app.sysmenu.data-filter' }),
        dataIndex: 'dataField',
        editable: true,
      },
      {
        title: formatMessage({ id: 'app.common.operate' }),
        align: 'center',
        dataIndex: 'operation',
        render: (text, record) =>
          this.state.dataSource.length >= 1 ? (
            <Popconfirm title={formatMessage({ id: 'app.common.confirm-delete' })} onConfirm={() => this.handleDelete(record)}>
              <a><Icon type="delete" />{formatMessage({ id: 'app.common.delete' })}</a>
            </Popconfirm>
          ) : null,
      },
    ];

    this.state = {
      dataSource: props.roleFieldDataSource.list,
      count: props.roleFieldDataSource.count
    };
  }

  handleDelete = record => {
    const dataSource = [...this.state.dataSource];
    this.setState({ dataSource: dataSource.filter(item => item.key !== record.key) });

    window.authorizeDispatch({
      type: 'sysMenu/deleteDataPermission',
      payload: {
        roleCode: record.roleCode,
        menuCode: this.props.values.menuCode
      }
    }).then(response => {
      if (response.message === 'success') {
        message.success(formatMessage({ id: 'app.common.delete-success' }));
      } else {
        message.warning(response.message);
      }
    });
  };

  handleAdd = () => {
    const { count, dataSource } = this.state;
    const newData = {
      key: count,
      roleCode: `-`,
      dataField: `-`,
    };
    this.setState({
      dataSource: [...dataSource, newData],
      count: count + 1,
    });
  };

  handleSave = row => {
    const newData = [...this.state.dataSource];
    const index = newData.findIndex(item => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    this.setState({ dataSource: newData });

    if (row.roleCode !== '-' && row.dataField !== '-') {
      let roleCodeArray = [];
      for (let key in newData) {
        roleCodeArray.push(newData[key].roleCode);
      }
      let newRoleCodeArray = roleCodeArray.join(",") + ",";
      for (let i = 0; i < roleCodeArray.length; i++) {// 判断角色编码是否重复
        if (newRoleCodeArray.replace(roleCodeArray[i] + ",", "").indexOf(roleCodeArray[i] + ",") > -1) {
          message.warning(formatMessage({ id: 'app.sysmenu.data-add' }));
          return;
        }
      }

      window.authorizeDispatch({
        type: 'sysMenu/authorizeMenuData',
        payload: {
          roleCode: row.roleCode,
          menuCode: this.props.values.menuCode,
          dataField: row.dataField
        }
      }).then(response => {
        if (response.message !== 'success') {
          message.warning(response.message);
        }
      });
    }
  };

  render() {
    const { updateModalVisible, handleUpdateModalVisible, values } = this.props;
    const { dataSource } = this.state;

    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };
    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });

    return (
      <div>
        <Drawer
          destroyOnClose
          title={values.menuName + formatMessage({ id: 'app.sysmenu.data-title' })}
          visible={updateModalVisible}
          width={720}
          onClose={() => handleUpdateModalVisible(false, values)}
          bodyStyle={{ paddingBottom: 80 }}
        >
          <div>
            <Button onClick={this.handleAdd} type="primary" style={{ marginBottom: 16 }}>
              {formatMessage({ id: 'app.common.add-row' })}
            </Button>
            <Table
              components={components}
              rowClassName={() => 'editable-row'}
              bordered
              dataSource={dataSource}
              columns={columns}
            />
          </div>
        </Drawer>
      </div>
    );
  }
}

/* eslint react/no-multi-comp:0 */
@connect(({ dataPermission, loading }) => ({
  dataPermission,
  loading: loading.models.dataPermission,
}))
@Form.create()
class DataPermission extends PureComponent {
  state = {
    updateModalVisible: false,
    selectedRows: [],
    formValues: {},
    updateFormValues: {},
    roleFieldDataSource: {},
    roleData: [],
    hiddenMenuButton: localStorage.getItem('mscode_menubutton')
  };

  columns = [
    {
      title: formatMessage({ id: 'app.sysmenu.menu-name' }),
      dataIndex: 'menuName'
    },
    {
      title: formatMessage({ id: 'app.sysmenu.menu-code' }),
      dataIndex: 'menuCode'
    },
    {
      title: formatMessage({ id: 'app.sysmenu.menu-icon' }),
      dataIndex: 'menuIcon'
    },
    {
      title: formatMessage({ id: 'app.sysmenu.menu-path' }),
      copyable: true,
      ellipsis: true,
      dataIndex: 'menuPath'
    },
    {
      title: formatMessage({ id: 'app.sysmenu.menu-status' }),
      dataIndex: 'menuStatusCn'
    },
    {
      title: formatMessage({ id: 'app.sysmenu.menu-sequence' }),
      dataIndex: 'menuSequence'
    },
    {
      title: formatMessage({ id: 'app.common.operate' }),
      align: 'center',
      render: (text, record) => (
        <Fragment>
          {this.state.hiddenMenuButton.indexOf('datapermission:authorize') !== -1 ? null :
            <a onClick={() => this.handleUpdateModalVisible(true, record)}><Icon type="safety-certificate" />{formatMessage({ id: 'app.common.authorize' })}</a>
          }
        </Fragment>
      )
    }
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    window.authorizeDispatch = dispatch;
    dispatch({
      type: 'dataPermission/fetch'
    });
    dispatch({
      type: 'dataPermission/fetchRole'
    });
  }

  handleBasicTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'dataPermission/fetch',
      payload: params
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {}
    });
    dispatch({
      type: 'dataPermission/fetch',
      payload: {}
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows
    });
  };

  handleSearch = e => {
    if (e) {
      e.preventDefault();
    }
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue
      };
      this.setState({
        formValues: values
      });
      dispatch({
        type: 'dataPermission/fetch',
        payload: values
      });
    });
  };

  handleUpdateModalVisible = (flag, record) => {
    if (flag == true) {
      const { dispatch } = this.props;
      dispatch({
        type: 'dataPermission/fetchRoleFieldData',
        payload: {
          menuCode: record.menuCode
        }
      }).then(response => {
        this.setState({
          updateModalVisible: !!flag,
          updateFormValues: record || {}
        });
      });
    } else {
      this.setState({
        updateModalVisible: !!flag
      });
    }
  };

  renderSimpleForm() {
    const { form: { getFieldDecorator } } = this.props;

    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label={formatMessage({ id: 'app.sysmenu.menu-name' })}>
              {getFieldDecorator('menuName')(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label={formatMessage({ id: 'app.sysmenu.menu-path' })}>
              {getFieldDecorator('menuPath')(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" icon="search">
                {formatMessage({ id: 'app.common.query' })}
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset} type="primary" icon="reload">
                {formatMessage({ id: 'app.common.reset' })}
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const { dataPermission: { data, roleFieldData, roleSelectData }, loading } = this.props;
    const { /**selectedRows,**/ updateModalVisible, updateFormValues } = this.state;
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible
    };
    let roleFieldDataSource;
    if ({ roleFieldData }.roleFieldData) {
      roleFieldDataSource = { roleFieldData }.roleFieldData;
    }
    if ({ roleSelectData }.roleSelectData) {
      window.roleData = { roleSelectData }.roleSelectData;
    }
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.handleSelectRows(selectedRows);
      }
    };
    return (
      <PageHeaderWrapper content={formatMessage({ id: 'app.sysmenu.data-manage' })}>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <ProTable
              bordered={true}
              search={false}
              rowKey={record => record.id}
              rowSelection={rowSelection}
              loading={loading}
              dataSource={data ? data.list : []}
              pagination={data ? data.pagination : {}}
              columns={this.columns}
              onChange={this.handleBasicTableChange}
              options={{
                density: true,
                reload: () => {
                  this.handleSearch();
                },
                fullScreen: true,
                setting: true,
              }}
            />
          </div>
        </Card>
        {updateFormValues && Object.keys(updateFormValues).length ? (
          <UpdateForm
            key={Math.random()}
            {...updateMethods}
            updateModalVisible={updateModalVisible}
            values={updateFormValues}
            roleFieldDataSource={roleFieldDataSource}
          />
        ) : null}
      </PageHeaderWrapper>
    );
  }
}

export default DataPermission;
